package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private EmpService empService;

    //分页条件查询班级表（clazz）
    @Override
    public PageResult<Clazz> getPageResult(ClazzQueryParam param) {
        Page<Clazz> page = Page.of(param.getPage(), param.getPageSize());
        // 根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        // 使用LambdaQuery来构建查询条件，并返回分页结果
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Clazz::getName, param.getName())
                .between(param.getBegin() != null && param.getEnd() != null, Clazz::getEndDate, param.getBegin(), param.getEnd())
                .page(page);


        // 添加班主任名称(clazz表中的master_id等于emp表中的id)
        List<Clazz> clazzs = page.getRecords();
        clazzs.forEach(clazz -> {
            Emp emp = empService.getById(clazz.getMasterId());
            if (emp != null) {
                clazz.setMasterName(emp.getName());
            }
        });

        /*当前时间小于beginDate时，状态为未开班。
        当前时间大于beginDate小于endDate时，状态为已开班
        当前时间大于endDate时，状态为已结课*/
        clazzs.forEach(clazz -> {
            if (clazz.getBeginDate() != null && clazz.getEndDate() != null) {
                if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                    clazz.setStatus("未开班");
                } else if (LocalDate.now().isAfter(clazz.getBeginDate()) && LocalDate.now().isBefore(clazz.getEndDate())) {
                    clazz.setStatus("已开班");
                } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                    clazz.setStatus("已结课");
                }
            }
        });


        return new PageResult<>(page.getTotal(), clazzs);
    }

}
